package com.rxt.thermopro.ui.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import androidx.core.view.isVisible
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.app.common.base.BaseFragment
import com.app.common.viewmodel.BaseViewModel
import com.rxt.thermopro.R
import com.rxt.thermopro.app.LocalDataDao
import com.rxt.thermopro.bean.EventAlarmTextData
import com.rxt.thermopro.viewmodel.DeviceStatusViewModel
import com.rxt.thermopro.viewmodel.TimerViewModel
import kotlinx.android.synthetic.main.fragment_timer.*

class TimerFragment : BaseFragment<TimerViewModel>() {
    override fun layoutId(): Int {
        return R.layout.fragment_timer
    }

    companion object {
        private const val ARG_POSITION = "currentPosition"
        private const val ARG_ADDRESS = "address"

        fun newInstance(position: Int): TimerFragment {
            return TimerFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_POSITION, position)
                }
            }
        }

        fun newInstance(position: Int, address: String): TimerFragment {
            return TimerFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_POSITION, position)
                    putString(ARG_ADDRESS, address)
                }
            }
        }
    }

    private var currentPosition = 0
    private var mAddress = ""
    private lateinit var mDeviceStatusViewModel: DeviceStatusViewModel

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        currentPosition = arguments?.getInt(ARG_POSITION, 0) ?: 0
        mAddress = arguments?.getString(ARG_ADDRESS, "") ?: ""
        mDeviceStatusViewModel =
            ViewModelProvider(requireActivity()).get(DeviceStatusViewModel::class.java)
        numPicker.apply {
            maxValue = 23
            minValue = 0
        }
        numPicker1.apply {
            maxValue = 59
            minValue = 0
        }
        numPicker2.apply {
            maxValue = 59
            minValue = 0
        }

        when (currentPosition) {
            0 -> {
                if (mDeviceStatusViewModel.blockTime1.isNotEmpty()) {
                    updateTime(mDeviceStatusViewModel.blockTime1[mAddress]!!)
                }
                timerEdit.setText(LocalDataDao.INSTANCE.getAlarmText1(mAddress))

                mDeviceStatusViewModel.alarmClock1.observeForever( Observer {
//                    if (it.containsKey(mAddress)) {
//                        updateTime(it[mAddress] ?: "")
//                    }
                    if (it.containsKey(mAddress)) {
                        mViewModel.alarmClockText1.postValue(hashMapOf<Long, EventAlarmTextData>().apply {
                            this[System.currentTimeMillis()] = EventAlarmTextData(
                                mAddress, it[mAddress] ?: "0:0:0"
                            )
                        })
                    }
                })
                mViewModel.alarmClockText1.observeInFragment(this, Observer {
                    val alarmData = it.values.last()
                    if (alarmData.address == mAddress) {
                        updateTime(alarmData.alarmText)
                    }
                })

            }
            1 -> {
                if (mDeviceStatusViewModel.blockTime2.isNotEmpty()) {
                    updateTime(mDeviceStatusViewModel.blockTime2[mAddress]!!)
                }
                timerEdit.setText(LocalDataDao.INSTANCE.getAlarmText2(mAddress))

                mDeviceStatusViewModel.alarmClock2.observeForever( Observer {
                    if (it.containsKey(mAddress)) {
                        mViewModel.alarmClockText2.postValue(hashMapOf<Long, EventAlarmTextData>().apply {
                            this[System.currentTimeMillis()] = EventAlarmTextData(
                                mAddress, it[mAddress] ?: "0:0:0"
                            )
                        })
                    }
                })

                mViewModel.alarmClockText2.observeInFragment(this, Observer {
                    val alarmData = it.values.last()
                    if (alarmData.address == mAddress) {
                        updateTime(alarmData.alarmText)
                    }
                })
            }
            2 -> {
                if (mDeviceStatusViewModel.blockTime3.isNotEmpty()) {
                    updateTime(mDeviceStatusViewModel.blockTime3[mAddress]!!)
                }
                timerEdit.setText(LocalDataDao.INSTANCE.getAlarmText3(mAddress))

                mDeviceStatusViewModel.alarmClock3.observeForever( Observer {
                    if (it.containsKey(mAddress)) {
                        mViewModel.alarmClockText3.postValue(hashMapOf<Long, EventAlarmTextData>().apply {
                            this[System.currentTimeMillis()] = EventAlarmTextData(
                                mAddress, it[mAddress] ?: "0:0:0"
                            )
                        })
                    }
                })

                mViewModel.alarmClockText3.observeInFragment(this, Observer {
                    val alarmData = it.values.last()
                    if (alarmData.address == mAddress) {
                        updateTime(alarmData.alarmText)
                    }
                })
            }
            3 -> {
                if (mDeviceStatusViewModel.blockTime4.isNotEmpty()) {
                    updateTime(mDeviceStatusViewModel.blockTime4[mAddress]!!)
                }
                timerEdit.setText(LocalDataDao.INSTANCE.getAlarmText4(mAddress))

                mDeviceStatusViewModel.alarmClock4.observeForever( Observer {
                    if (it.containsKey(mAddress)) {
                        mViewModel.alarmClockText4.postValue(hashMapOf<Long, EventAlarmTextData>().apply {
                            this[System.currentTimeMillis()] = EventAlarmTextData(
                                mAddress, it[mAddress] ?: "0:0:0"
                            )
                        })
                    }
                })

                mViewModel.alarmClockText4.observeInFragment(this, Observer {
                    val alarmData = it.values.last()
                    if (alarmData.address == mAddress) {
                        updateTime(alarmData.alarmText)
                    }
                })
            }
        }

        if (mDeviceStatusViewModel.isBlockWorking(currentPosition, mAddress)) {
            viewStart.text = "Stop"

            enableView.isVisible = true
            timerEdit.clearFocus()
        } else {
            viewStart.text = "Start"

            enableView.isVisible = false
        }

        initListener()
    }

    private fun updateTime(it: String) {
        if (it.isNotEmpty() && it.contains(":")) {
            val h = it.split(":")[0].toInt()
            val m = it.split(":")[1].toInt()
            val s = it.split(":")[2].toInt()
            numPicker.value = h
            numPicker1.value = m
            numPicker2.value = s
        } else {

            enableView.isVisible = false
            viewStart.text = "Start"
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initListener() {
        backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }

        numPicker.setOnValueChangedListener { picker, oldVal, newVal ->

        }
        numPicker1.setOnValueChangedListener { picker, oldVal, newVal ->

        }
        numPicker2.setOnValueChangedListener { picker, oldVal, newVal ->

        }

        timerEdit.filters = arrayOf(InputFilter.LengthFilter(200))
        timerEdit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                textNum.text = "${s.toString().length}/200"
            }

        })

        viewReset.setOnClickListener {
            viewStart.text = "Start"

            enableView.isVisible = false
            timerEdit.setText("")
            mDeviceStatusViewModel.resetBlockWorking(currentPosition, mAddress)
        }

        viewStart.setOnClickListener {
            if (numPicker.value == 0 && numPicker1.value == 0 && numPicker2.value == 0) {
                return@setOnClickListener
            }
            if (mDeviceStatusViewModel.isBlockWorking(currentPosition, mAddress)) {
                viewStart.text = "Start"

                enableView.isVisible = false
                mDeviceStatusViewModel.stopBlockWorking(
                    mAddress,
                    currentPosition,
                    "${numPicker.value}:${numPicker1.value}:${numPicker2.value}",
                    timerEdit.text.toString()
                )
            } else {
                viewStart.text = "Stop"

                enableView.isVisible = true
                timerEdit.clearFocus()
                mDeviceStatusViewModel.startAlarmClock(
                    mAddress,
                    currentPosition,
                    "${numPicker.value}:${numPicker1.value}:${numPicker2.value}",
                    timerEdit.text.toString()
                )
            }
        }
    }
}